const url = require('url'),
http = require('http'),
https = require('https'),
env = require('jsdom').env,
jquery = require('jquery'),
iconv = require('iconv-lite'),
log = require('../util/log');

const parsedUrl = url.parse('https://jingyan.baidu.com/article/4f7d5712d3701a1a20192786.html', true),
options = {
	host: parsedUrl.hostname,
	port: parsedUrl.port,
	path: parsedUrl.pathname,
	method: 'GET'
}
if (parsedUrl.search)
	options.path += "?" + parsedUrl.search;
new Promise(resolve => {
	var client = parsedUrl.protocol == 'https:' ? https : http;
	const req = client.request(options, (res) => {
			var body = []
			res.on('data', (chunk) => {
				body.push(chunk)
			}).on('end', () => {
				var html = Buffer.concat(body).toString();
				if (!html) {
					resolve('获取title失败')
					return
				}
				var start = html.indexOf('charset=');
				if (start != -1) {
					start += 8
					if (html.substring(start, start + 8) == '"gb2312"' || html.substring(start, start + 6) == 'gb2312') {
						html = iconv.decode(Buffer.concat(body), 'GBK')
					}
				}
				env(html, (errors, window) => {
					if (errors) {
						log(errors)
						return
					}
					var $ = jquery(window);
					resolve($('title').text())
				})
			}).on('error', (err) => {
				log(err)
			})
		});
	req.on('error', (err) => {
		log(err)
		resolve('获取title失败')
	})
	req.end()
}).then(title => {
	log(title)
}).catch (err => {
	log(err)
})
